<template>
  <div class="question-purchase">
    <div class="purchase">
      <div class="purchase-detail">
        <p class="purchase-detail-title">题库购买</p>
        <div class="purchase-detail-content">
          <div class="purchase-detail-left">
            <img class="purchase-detail-cover" :src="question_obj.cover" alt="">
          </div>
          <div class="purchase-detail-right">
            <h1 class="purchase-detail-name" :title="question_obj.questionGroupName">{{question_obj.questionGroupName}}</h1>
            <p class="purchase-detail-coursename">{{question_obj.courseName}}</p>
            <p class="purchase-detail-price">
              <span>￥{{price}} / {{year}}</span>
              <span class="old_price" v-if="isDiscount">￥{{question_obj.price}} / {{year}}</span>
            </p>
          </div>
        </div>
        <div class="purchase-bottom">
          <p class="purchase-bottom-title">需支付金额</p>
          <div class="purchase-bottom-row">
            <div class="purchase-bottom-row-left">课程价格</div>
            <div class="purchase-bottom-row-right">￥{{price}}</div>
          </div>
          <div class="purchase-bottom-row">
            <div class="purchase-bottom-row-left">应付金额</div>
            <div class="purchase-bottom-row-right">￥{{price}}</div>
          </div>
          <div class="purchase-pay-list">
            <span style="margin-right:20px;">支付方式</span>
            <RadioGroup v-model="payType">
              <Radio :label="1">
                <span class="ye-pay">
                  <img src="/img/pc/ye.png" alt="" />
                  余额
                </span>
              </Radio>
              <Radio :label="2" v-if="!question_obj.isFree">
                <span class="wx-pay">
                  <img src="/img/pc/weixin.png" alt="" />
                  微信
                </span>
              </Radio>
              <Radio :label="3" v-if="!question_obj.isFree">
                <span class="zfb-pay">
                  <img src="/img/pc/zhifubao.png" alt="" />
                  支付宝
                </span>
              </Radio>
            </RadioGroup>
          </div>
          <div class="purchase-buy-btn" @click="handlePay">立即付款</div>
        </div>
      </div>
    </div>
    <Modal v-model="is_show_wechat_pay" :title="$t('locale.pc.personal.t74')">
      <div style="text-align:center;">
        <img :src="wechat_pay_qr" />
      </div>
    </Modal>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import { getQuestionBankOne } from "~/api/v2-question-bank/question-bank";
import { buyQuestionBank } from "~/api/v2-question-bank/order.js";
import { generateOrder,getCourseBuyToPcAlipay } from "~/api/order";
import { baseUrl, socketUrl } from "~/config/conf";
export default {
  name: "question-purchase",
  data() {
    return {
      question_obj:{},
      payType: 1,
      wechat_pay_qr:"",
      is_show_wechat_pay:false,
      websock: null,
      timer: null, //节流计时器
      socketFailedCount: 0, //socket重连计数器
      orderNo:"",
      pay_success:false,
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
    }),
    question_id() {
      return this.$route.query.qid;
    },
    price(){
      if(this.question_obj.isFree){
        return 0.00;
      }else if(this.isDiscount){
        return this.question_obj.discountPrice;
      }else{
        return this.question_obj.price;
      }
    },
    isDiscount(){
      if(this.question_obj.isDiscount == 1){
        let current_time = new Date().getTime();
        let discount_start_time = new Date(this.question_obj.discountStartTime).getTime();
        let discount_end_time = new Date(this.question_obj.discountEndTime).getTime();
        return discount_start_time <= current_time && current_time < discount_end_time;
      }else{
        return false;
      }
      
    },
    year(){
      if(this.question_obj.effectiveTime){
        return this.question_obj.effectiveTime + "年";
      }else{
        return "0年";
      }
      // if(this.question_obj.isLong == 1){
      //   return "长期";
      // }else{
      //   return this.question_obj.effectiveTime + "年";
      // }
    },
  },
  methods: {
    ...mapActions(["getMineV2QuestionBankList"]),
    ...mapMutations([
      "SET_IS_LOADING",
      "UPDATE_USERINFO",
      "UPDATE_QUESTION_LIST"
    ]),
    initWebSocket() {
      if (process.client) {
        if ("WebSocket" in window) {
          //初始化weosocket
          const wsuri = socketUrl + "buyOrderInfo/" + this.orderNo;
          this.websock = new WebSocket(wsuri);
          this.websock.onmessage = this.websocketonmessage;
          this.websock.onopen = this.websocketonopen;
          this.websock.onerror = this.websocketonerror;
          this.websock.onclose = this.websocketclose;

          window.addEventListener("beforeunload", this.closeConnection, false);
        } else {
          this.$Message.error(this.$t("locale.pc.personal.t134"));
        }
      }
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      clearTimeout(this.timer);
      this.timer = null;
      this.socketFailedCount = 0;
    },
    websocketonerror() {
      //连接建立失败重连
      console.log("socket连接失败！");
      this.retryConnectSocket();
    },
    websocketonmessage(e) {
      //数据接收
      console.log("收到socket:", e);
      console.log(e.data || e);
      try {
        const result = JSON.parse(e.data);
        if (result.code == 200) {
          let questionId = result.data.productId;
          // 付款成功
          this.pay_success = true;
          this.is_show_wechat_pay = false;
          this.paySuccess(questionId);
        } else {
          this.$Message.error(this.$t("locale.pc.personal.t128"));
        }
      } catch (e) {
        console.log(e);
      }
    },
    websocketsend(Data) {
      //数据发送
      this.websock.send(Data);
    },
    async websocketclose(e) {
      //关闭
      console.log("断开连接", e);
      this.retryConnectSocket();
    },
    closeConnection() {
      return new Promise((res, rej) => {
        try {
          window.removeEventListener("beforeunload", this.closeConnection);
          this.websock && this.websock.close();

          if(this.timer){
            clearTimeout(this.timer);
            this.timer = null;
            this.socketFailedCount = 0;
          }
        } catch (e) {
          console.log("关闭socket错误：", e);
        }
        res();
      }).then();
    },
    retryConnectSocket() {
      this.debounce(async () => {
        this.socketFailedCount = this.socketFailedCount + 1;
        if (this.socketFailedCount < 10) {
          await this.closeConnection();
          this.initWebSocket();
        } else {
          console.info("websocket fail to connection , please retry later!");
          this.timer = null;
        }
      }, 3000);
    },
    debounce(fn, wait) {
      return !(() => {
        if (this.timer !== null) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(fn, wait);
      })();
    },
    // 获取题库详情
    async getQueationDetail(){
      this.SET_IS_LOADING(true);
      let result = await getQuestionBankOne(this.question_id);
      console.log("获取当前题库：", result);
      if (result && result.data && result.data.code == 200) {
        const { data } = result.data;
        if (data) {
          this.question_obj = data;
        }
      }
      this.SET_IS_LOADING(false);
    },
    // 购买成功回调
    paySuccess(questionId){
      let id = questionId || this.question_id;
      this.getMineV2QuestionBankList();
      this.$Message.success("购买成功");
      this.$router.replace("/question-detail?id=" + id);
    },
    // 处理价格
    turnString(num) {
      var re = /^[0-9]+$/;
      var re2 = /^[0-9]+(\.[0-9]{1})$/;
      if (re.test(num)) {
        num += ".00";
      }
      if (re2.test(num)) {
        num += "0";
      }
      return num;
    },
    async handlePay() {
      let __price__ = Number(
        this.question_obj.isFree
          ? 0
          : this.isDiscount
          ? this.question_obj.discountPrice
          :this.question_obj.price
      ).toFixed(2);
      console.log(__price__);
      if (this.payType == 1) {
        console.log("余额支付");
        const successFun = () => {
          this.$Modal.confirm({
            title: this.$t("locale.pc.mycourse.coursebuy.t8"),
            content:
              this.$t("locale.pc.mycourse.coursebuy.t9") +
              (__price__ - this.user_info.balance) +
              this.$t("locale.pc.mycourse.coursebuy.t11"),
            okText: this.$t("locale.pc.mycourse.coursebuy.t10"),
            onOk: () => {
              this.$router.push({
                path: "personal?action=my_account",
                query: {
                  num: __price__ - this.user_info.balance,
                  rdurl: this.$route.fullPath
                }
              });
            }
          });
        };
        this.$Modal.confirm({
          title: this.$t("locale.pc.mycourse.coursebuy.t12"),
          content:
            this.$t("locale.pc.mycourse.coursebuy.t13") +
            __price__ +
            this.$t("locale.pc.mycourse.coursebuy.t14"),
          onOk: async () => {
            // console.log(__price__, this.user_info.balance);
            if (__price__ > this.user_info.balance) {
              this.$nextTick(() => {
                setTimeout(() => {
                  successFun();
                }, 500);
              });
            } else {
              this.SET_IS_LOADING(true);
              let params = {
                questionGroupId: this.question_id,
                userId: this.user_info.id,
                price: this.turnString(__price__),
                ip: returnCitySN.cip
              };
              let result = await buyQuestionBank(params);
              console.log("题库购买：", result);
              if (result && result.data && result.data.code == 200) {
                this.$Message.success("购买成功！");
                this.getMineV2QuestionBankList();
                this.$router.replace("/question-detail?id=" + this.question_id);
              } else {
                if (result && result.data && result.data.code == 420) {
                  this.$Message.warning("余额不足，购买失败!");
                } else if (result && result.data && result.data.code == 1001) {
                  this.$Message.error(result.data.msg);
                } else {
                  this.$Message.error("购买失败，请稍后重试！");
                }
              }
              this.SET_IS_LOADING(false);
            }
          },
          onCancel: () => {
            this.$Message.success(this.$t("locale.pc.mycourse.coursebuy.t18"));
          }
        });
      } else if (this.payType == 2) {
        let params = {
          questionGroupId: this.question_id,
          userId: this.user_info.id,
          price: this.turnString(__price__),
          ip: returnCitySN.cip,
          type:4,
          payType:2
        };
        let result = await generateOrder(params);
        if(result && result.data && result.data.code == 200){
          const { orderNo } = result.data.data;
          this.orderNo = orderNo;
          this.wechat_pay_qr = `${baseUrl}/buyOrderInfo/wx/pc?orderNo=${orderNo}`;
          this.initWebSocket();
          this.is_show_wechat_pay = true;
        }else{
          this.$Message.error("系统错误");
        }
        console.log("微信支付");
      } else if (this.payType == 3) {
        let params = {
          questionGroupId: this.question_id,
          userId: this.user_info.id,
          price: this.turnString(__price__),
          ip: returnCitySN.cip,
          type:4,
          payType:3
        };
        let result = await generateOrder(params);
        if(result && result.data && result.data.code == 200){
          const { orderNo } = result.data.data;
          this.orderNo = orderNo;
          let resultPay = await getCourseBuyToPcAlipay(this.orderNo);
          if (resultPay && resultPay.data && resultPay.data.code == 200) {
            window.location.href = resultPay.data.data;
          } else {
            this.$Message.error(
              this.$t("locale.pc.personal.t128") + resultPay.data
                ? resultPay.data.msg
                : null
            );
          }
        }else{
          this.$Message.error("系统错误");
        }
        console.log("支付宝支付");
        
      } else {
        this.$Message.warning("请选择您的支付方式");
      }
      return;
    }
  },
  deactivated(){
    this.timer = null;
    this.socketFailedCount = 0;
    this.closeConnection();
  },
  destroyed(){
    this.timer = null;
    this.socketFailedCount = 0;
    this.closeConnection();
  },
  created() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/login");
        return;
      }
      this.getQueationDetail();
      if(this.$route.query.isSuccess == 1){
        // 支付成功--获取题库id
        this.pay_success = true;
        this.paySuccess();
      }
    }
  },
};
</script>
<style lang="scss">
.question-purchase{
  .ivu-radio-group {
    display: flex;
  }
  .ivu-radio-wrapper.ivu-radio-group-item {
    display: flex;
    align-items: center;
  }
}
</style>
<style lang="scss" scoped>
.question-purchase{
    position: relative;
    width: 100%;
    min-height: 100vh;
    padding: 30px 0;
    .purchase{
      width: 1200px;
      margin: 0 auto;
      padding: 0 20px;
      background-color: #fff;
      .purchase-detail{
        padding: 30px 0;
        border-bottom: 1px solid #eee;
        .purchase-detail-title{
          font-size: 16px;
          color: #333;
          margin-bottom: 15px;
        }
        .purchase-detail-content{
          display: flex;
          justify-content: space-between;
          .purchase-detail-left{
            width: 180px;
            height: 120px;
            .purchase-detail-cover{
              display: block;
              width: 100%;
              height: 100%;
            }
          }
          .purchase-detail-right{
            width: 950px;
            height: 120px;
            .purchase-detail-name{
              line-height: 1.5;
              font-size: 22px;
              color: #000;
              font-weight: 400;
              overflow: hidden;
              white-space: nowrap;
              -o-text-overflow: ellipsis;
              text-overflow: ellipsis;
            }
            .purchase-detail-coursename{
              display: inline-block;
              font-size: 14px;
              color: #999;
              line-height: 1.5;
              overflow: hidden;
              white-space: nowrap;
              -o-text-overflow: ellipsis;
              text-overflow: ellipsis;
            }
            .purchase-detail-price{
              margin-top: 5px;
              font-size: 16px;
              color: #ff8a8a;
              line-height: 24px;
              .old_price{
                color: #999;
                text-decoration: line-through;
              }
            }
          }
        }
        .purchase-bottom{
          padding: 30px 0 0;
          overflow: hidden;
          .purchase-bottom-title{
            margin-bottom: 20px;
            font-size: 16px;
            color: #000;
          }
          .purchase-bottom-row{
            display: flex;
            color: #000;
            line-height: 30px;
            font-size: 14px;
            .purchase-bottom-row-left{
              width: 85px;
            }
            .purchase-bottom-row-right{
              font-size: 14px;
            }
          }
          .purchase-pay-list {
            margin: 30px 0 22px;
            font-size: 16px;
            display: flex;
            align-items: center;
            .ye-pay,
            .wx-pay,
            .zfb-pay {
              padding: 0px 11px;
              margin-left: 15px;
              border-radius: 4px;
              font-size: 16px;
              display: inline-flex;
              align-items: center;
            }
            .ye-pay {
              border: 1px solid #515a6e;
              img {
                width: 30px;
                height: 30px;
                display: block;
              }
              margin-right: 20px;
            }
            .wx-pay {
              border: 1px solid #00c800;
              margin-right: 20px;
            }
            .zfb-pay {
              border: 1px solid #2194d3;
            }
          }
          .purchase-buy-btn{
            font-size: 16px;
            line-height: 40px;
            width: 120px;
            text-align: center;
            background-color: #f0423d;
            color: #fff;
            border-radius: 2px;
            cursor: pointer;
            float: right;
          }
        }
      }
    }
}
</style>
